<template>
  <div>
    <div class="cl-card" v-if="pagelistlayout === 'DefaultListPage'">
        <a-skeleton :loading="loading" avatar :paragraph="{ rows: 4 }" v-for="(item, index) in listData" :key="item.Id">
            <div class="row">
                <div class="col-lg-3 col-md-4 col-sm-12 cl-card-image">
                  <router-link :to="{ name: 'blogdetail', params: { columnid: columnid, blogid: item.Id }}">
                    <img v-lazy="item.CoverImageUrl" class="img-fluid" alt="">
                  </router-link>
                </div>
                <div class="col-lg-9 col-md-8 col-sm-12 cl-card-main">
                    <h3 class="cl-card-main-title">
                      <router-link :to="{ name: 'blogdetail', params: { columnid: columnid, blogid: item.Id }}">{{item.Title}}</router-link>
                    </h3>
                    <div class="cl-card-main-time">       
                      <span class="day">{{item.CreatedOnTime | formatDate('dd')}}</span>       
                      <span class="month fs-18">{{item.CreatedOnTime | formatDate('MM')}}<span class="fs-14">月</span></span>       
                      <span class="year fs-18 ml10">{{item.CreatedOnTime | formatDate('yyyy')}}</span>   
                    </div>
                    <p class="cl-card-main-info">{{item.ContentOverView}}</p>
                    <div class="cl-card-more">
                      <div class="f-fl"> 
                        <router-link :to="{ name: 'blogdetail', params: { columnid: columnid, blogid: item.Id }}">阅读更多...</router-link>
                      </div>
                      <div class="f-fr" style="position: relative; top: -5px;">    
                        <span class="read fs-18">
                          <i class="fa fa-eye"></i>               
                          <i class="num">{{getVisitCount(item.Id)}}</i>           
                        </span>      
                        <span class="ml20 fs-18"> 
                          <i class="fa fa-thumbs-o-up"></i>               
                          <i class="num">{{getLikeCount(item.Id)}}</i>    
                        </span>  
                      </div>
                    </div>
                </div>
            </div>
        </a-skeleton>
    </div>
    <!-- Image Gallery -->
    <div v-else-if="pagelistlayout === 'ImageGallery'">
      <a-skeleton :loading="loading" avatar :paragraph="{ rows: 4 }">
        <a-list item-layout="vertical" size="large" :data-source="listData">
        <div slot="footer"><b>所有图片未经允许不得转载。</b></div>
        <a-list-item slot="renderItem" key="item.Id" slot-scope="item, index">
          <template v-for="{ type, text } in imglistactions" slot="actions">
            <span :key="type">
              <a-icon :type="type" style="margin-right: 8px" />
              {{ getCountbyType(type, item.Id) }}
            </span>
          </template>
          <a-list-item-meta :description="item.ContentOverView">
            <img
              slot="avatar"
              width="108"
              :alt="item.Title"
              v-lazy="item.CoverImageUrl"
            />
            <router-link slot="title" :to="{ name: 'blogdetail', params: { columnid: columnid, blogid: item.Id }}">
              {{item.Title}}
            </router-link>
          </a-list-item-meta>
        </a-list-item>
      </a-list>
      </a-skeleton>
    </div>
    <nav aria-label="Page navigation">
      <a-pagination
        :pageSizeOptions="pagesizeOptions"
        :total="totalcount"
        showSizeChanger
        :pageSize="pagesize"
        v-model="page"
        @showSizeChange="onShowSizeChange"
      >
        <template slot="buildOptionText" slot-scope="props">
          <span>{{ props.value }}条/页</span>
        </template>
      </a-pagination>
    </nav>
  </div>
</template>

<script>
import { Pagination } from 'ant-design-vue';
import lodash from 'lodash'
import * as timeago from 'timeago.js';
import { mapState } from 'vuex'
import { getBlogList, getLanguageSupport } from '@/api'
export default {
  name: 'BlogList',
  components:{ 
    APagination : Pagination 
  },
  data() {
    return {
      loading: true,
      columnid: 0,
      pagelistlayout: 'DefaultListPage',
      page: 1,       //分页 当前页数
      pagesize: 20,  //分页 每页显示列数
      pagesizeOptions: ['10', '20', '30'],
      totalcount: 0, //后台返回分页列表记录总数
      listData: [],
      blogStatistics: [],
      imglistactions: [
        { type: 'eye', text: '0' },
        { type: 'like-o', text: '0' },
        { type: 'clock-circle', text: '0' },
      ],
    };
  },
  computed: {
    ...mapState({
      mainmenu: state => state.navmenus,
      language: state => state.language
    }),
  },
  mounted () {
      this.onLoadList()
  },
  watch: {      
    $route: function () {
      this.onLoadList()
    }
  },
  methods: {
    onLoadList() {
        const navimenus = this.mainmenu;
        let activeMenuItem = null;
        if(!lodash.isNil(this.$route.params.columnid)) { //List
            this.columnid = this.$route.params.columnid;
            if(typeof this.columnid === 'string') this.columnid = parseInt(this.$route.params.columnid);
            activeMenuItem = lodash.find(navimenus, ['Id', this.columnid])
            if(!lodash.isNil(activeMenuItem)) {
                if(activeMenuItem.PageSizeOptions !== null && activeMenuItem.PageSizeOptions !== "") {
                  const sizeArr = lodash.split(activeMenuItem.PageSizeOptions, ',')
                  if(sizeArr.length > 0)
                    this.pagesizeOptions = sizeArr.map((item) => {
                      return typeof item === 'string' ? item.trim() : item.toString()
                    })
                }
                this.pagesize = activeMenuItem.PageSize;
                this.pagelistlayout = activeMenuItem.LayoutListTemplate
                this.remoteLoadData();
            }
            else this.$router.push("bloghome")
        }
        else this.$router.push("bloghome")
    },
    remoteLoadData() {
        this.loading = true;
        let me = this;
        getBlogList(this.columnid, this.page, this.pagesize, 
            function(res) { //Success
                me.loading = false;
                me.totalcount = res.data.RecordsTotal
                me.listData = res.data.Data
                if(!lodash.isEmpty(res.data.CustomProperties)) {
                  const bloglistcount = res.data.CustomProperties.BlogStatistics                
                  if(bloglistcount !== null)
                    me.blogStatistics = bloglistcount
                }
            }, function(msg) { //Failure
                me.loading = false;
                me.$notification['error']({
                    message: '通知消息',
                    description: msg,
                });
            }
        );
    },
    /**
     * 分页组件当显示列表数据变化时触发
     */
    onShowSizeChange(current, pageSize) {
      this.pagesize = pageSize;
    },
    /**
     * 后台返回以博客Id，访问数量的统计数据形如：
     * "BlogStatistics": [
     *  {
     *    "Id": 10,
     *    "VisitCount": 0,
     *    "LikeCount": 4
     *  }
     * ]
     * 遍历分页列表Id获取对应Id的统计信息
     */
    filterBlogInfo(blogid) {
      if (typeof blogid === 'string') blogid = parseInt(blogid)
      if (blogid <= 0) return null
      const bloginfo = lodash.find(this.blogStatistics, ['Id', blogid]);
      return (typeof bloginfo === 'undefined') ? null : bloginfo;
    },
    /**
     * 数据说明同filterBlogInfo
     * 遍历分页列表Id获取对应Id的浏览量
     */
    getVisitCount(blogid) {
      if (!blogid) return 0
      const bloginfo = this.filterBlogInfo(blogid)
      return (bloginfo === null) ? 0 : bloginfo.VisitCount;
    },
    /**
     * 数据说明同filterBlogInfo
     * 遍历分页列表Id获取对应Id的点赞量
     */
    getLikeCount(blogid) {
      if (!blogid) return 0
      const bloginfo = this.filterBlogInfo(blogid)
      return (bloginfo === null) ? 0 : bloginfo.LikeCount;
    },
    /**
     * for image gallery
     */
    getCountbyType(type, blogid) {
      if(!type || !lodash.isString(type)) return 0;
      let count = 0;
      switch (type.toLowerCase()) {
        case 'eye': //浏览量
          count = this.getVisitCount(blogid);
          break;
        case 'like-o': //点赞量
          count = this.getLikeCount(blogid);
          break;
        case 'clock-circle': //时间戳 https://timeago.org/
          if(this.listData !== null && typeof listData === 'string') 
            this.listData = JSON.parse(this.listData);
          const blogitem = lodash.find(this.listData, ['Id', blogid]);
          if(blogitem !== null) {
            const local = getLanguageSupport(this.language);
            count = timeago.format(blogitem.UpdatedOnTime, local);
          } else count = 0;
          break;
        default:
          count = 0;
          break;
      }
      return count;
    }    
  }, // End of Methods
}
</script>

<style lang="less">
  .ant-pagination-item-active {
    background-color: #FF9400;
    border-color: #FF9400;
    color: #fff;

    &:hover a,
    &:focus a{
      color: #fff;
    }
    a { color: #fff;}
  }
  .ant-pagination-item {
    &:hover,
    &:focus {
      border-color: #FF9400;
    }
    &:hover a,
    &:focus a{
      color: #fff;
    }
  }
  .ant-list-item-action .anticon {
    position: relative;
    top: -3px;
  }
  .ant-list-item {
    background-color: #fff;
    margin: 0 0 18px 0;
    padding-left: 10px;
    border-bottom: 1px solid #e8e8e8;
  }
  .cl-cantainer .cl-card {
    background-color: inherit;
    .row {
      margin: 0 0 18px 0;
      padding: 8px;
      background-color: #fff;
    }
  }
</style>
